package com.heima.comment.service.impl;

import com.heima.comment.dto.ApCommentRepayVo;
import com.heima.comment.dto.CommentRepayDto;
import com.heima.comment.dto.CommentRepayLikeDto;
import com.heima.comment.dto.CommentRepaySaveDto;
import com.heima.comment.entity.*;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentRepayService;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CommentRepayServiceImpl implements ICommentRepayService {
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private GreenTextScan textScan;



    @Override
    public ResponseResult saveRepay(CommentRepaySaveDto dto) {
        if(dto==null||dto.getContent().length()>140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        User user = AppThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //安全过滤-阿里云审核
        try {
            Map map = textScan.greenTextScan(dto.getContent());
            String suggestion = (String) map.get("suggestion");
            if(suggestion.equals("block")){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ApCommentRepay commentRepay=new ApCommentRepay();
        commentRepay.setAuthorId(user.getUserId());
        ResponseResult<ApUser> apUserResponseResult = userFeign.getById(user.getUserId());
        if(apUserResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApUser apUser = apUserResponseResult.getData();
            commentRepay.setAuthorName(apUser.getName());
        }
        commentRepay.setCommentId(dto.getCommentId());
        commentRepay.setContent(dto.getContent());
        commentRepay.setLikes(0);
        commentRepay.setCreatedTime(new Date());
        //保存评论
        mongoTemplate.save(commentRepay);
        //讲评论表的回复数量+1
        Query commentQuery=new Query();
        commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentId()));
        Update update=new Update();
        update.inc("reply");
        mongoTemplate.updateFirst(commentQuery,update, ApComment.class);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {
        // 获取当前的用户
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 构建点赞记录
        ApCommentRepayLike like = new ApCommentRepayLike();
        like.setAuthorId(user.getUserId());
        like.setCommentRepayId(dto.getCommentRepayId());
        like.setOperation(dto.getOperation());
        // 判断当前用户是否已经对这篇评论有过点赞记录
        Query query = new Query();
        query.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        query.addCriteria(Criteria.where("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (one == null) {
            // 保存点赞记录
            mongoTemplate.save(like);
            // 更新回复表的点赞数量+1
            Query commentQuery = new Query();
            commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentRepayId()));
            Update update = new Update();
            update.inc("likes");
            mongoTemplate.updateFirst(commentQuery, update, ApCommentRepay.class);
        } else {
            if (one.getOperation() != dto.getOperation()) {
                // 判断是点赞还是取消点赞
                int add = 1;
                // 修改ApCommentLike的状态
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
                // 更新评论表的点赞数量
                if (dto.getOperation() == 1) {
                    add = -1;
                }
                Query commentQuery = new Query();
                commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentRepayId()));
                Update update = new Update();
                update.inc("likes", add);
                mongoTemplate.updateFirst(commentQuery, update, ApCommentRepay.class);
            }
        }
        return ResponseResult.okResult();
    }

    /**
     * 加载回复列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentRepayDto dto) {

        if (dto.getSize() == null || dto.getSize() <= 0 || dto.getSize() >= 50) {
            dto.setSize(10);
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()));
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
        // 分页 和 排序
        Pageable page = PageRequest.of(0, dto.getSize(), Sort.Direction.DESC, "createdTime");
        query.with(page);
        List<ApCommentRepay> apComments = mongoTemplate.find(query, ApCommentRepay.class);
        // 判断当前用户是否登录
        User user = AppThreadLocalUtil.get();
        List<ApCommentRepayLike> likes = new ArrayList<>();
        // 登录用户需要查看当前返回的列表中是否已经有点赞记录
        if (user != null) {
            List<String> commentIds = new ArrayList<>();
            for (ApCommentRepay apComment : apComments) {
                commentIds.add(apComment.getId());
            }
            Query likeQuery = new Query();
            likeQuery.addCriteria(Criteria.where("authorId").is(user.getUserId()));
            likeQuery.addCriteria(Criteria.where("commentRepayId").in(commentIds));
            likeQuery.addCriteria(Criteria.where("operation").is(0));
            likes = mongoTemplate.find(likeQuery, ApCommentRepayLike.class);
        }
        List<String> existCommentIds = new ArrayList<>();
        for (ApCommentRepayLike like : likes) {
            existCommentIds.add(like.getCommentRepayId());
        }
        // 返回vo对象集合
        List<ApCommentRepayVo> vos = new ArrayList<>();
        for (ApCommentRepay apComment : apComments) {
            ApCommentRepayVo vo = new ApCommentRepayVo();
            BeanUtils.copyProperties(apComment, vo);
            // 默认没有点赞,设置为1
            vo.setOperation(1);
            if (existCommentIds.contains(apComment.getId())) {
                vo.setOperation(0);
            }
            vos.add(vo);
        }
        return ResponseResult.okResult(vos);
    }
}
